package br.com.wuo.genericInventary.view;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.Timer;

import com.thingmagic.ReadListener;
import com.thingmagic.Reader;
import com.thingmagic.TagReadData;

import net.miginfocom.swing.MigLayout;
import br.com.wuo.genericInventary.application.Resources;
import br.com.wuo.genericInventary.application.ShelfReader;
import br.com.wuo.genericInventary.model.Item;

public class GenericInventory extends JFrame implements ReadListener{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private JMenuItem itemIniciar, itemExit, itemConfig;
	private Object[][] content;
	private JTable tblItems;
	private JLabel background;
	private JScrollPane jScrollPane;
	private Properties properties;
	
	private ShelfReader reader;
    private boolean firstUpdate;
    private Timer timer;
    private Collection<String> currentEpcs;
    private Collection<String> previousEpcs;
    private Map<String, String> itemName;
    private Map<String, Integer> itemQuantity;
    private ArrayList<Item> items;
	
	public GenericInventory() {
		super("Generic Inventory");
    	
		try {
			Resources.verifyResources();
			properties = Resources.getProperties();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			System.exit(1);
		}
		
        initialize();
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(800, 600);
        setExtendedState(JFrame.MAXIMIZED_VERT);
        addListener();
		
	}
	
	public void initialize() {
        setLayout(new MigLayout("wrap 2", "10px[][]10px", ""));
        
        this.firstUpdate = true;
        createAndLoadItemsMap();
        
        
        String[] colunas = {"ITEM", "QUANTIDADE"};
        content = new Object[0][2];

        tblItems = new JTable(content, colunas);
        
        jScrollPane = new JScrollPane();
        jScrollPane.setViewportView(tblItems);
        
        
		try {
			background = new JLabel(new ImageIcon(ImageIO.read(this.getClass().getClassLoader().getResourceAsStream("images/logos2.png"))));
	    	background.setLayout(new FlowLayout());
		} catch (IOException e) {
			e.printStackTrace();
		}
        
        
        
        JMenuBar menuBar = new JMenuBar();
        JMenu menuFile = new JMenu("Arquivo");
        JMenu menuConfig = new JMenu("Configuração");
        itemIniciar = new JMenuItem("Iniciar");
        itemExit = new JMenuItem("Sair");
        itemConfig = new JMenuItem("Configuração");
        menuFile.add(itemIniciar);
        menuFile.add(itemExit);
        menuConfig.add(itemConfig);
        menuBar.add(menuFile);
        menuBar.add(menuConfig);
        setJMenuBar(menuBar);
        
        add(background, "wrap");
        add(jScrollPane, "w 520!, h 180!");

        pack();
    }
	
	public void addListener() {
		itemIniciar.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				
				
				try {
					reader = new ShelfReader(properties.getProperty("usb.port"));
					reader.connect();
					shelfCount();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				
				
			}
		});
		
        itemExit.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent e) {
                dispose();
            }
        });
        
        itemConfig.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				new configView().setVisible(true);
				
			}
		});
	}
	
	private void shelfCount(){
    	
		reader.addReadListener(this);
		
    	timer = new Timer(Integer.parseInt(properties.getProperty("interval.seconds"))*1000 , new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				try {
					
					reader.startReading();
					Thread.sleep(Integer.parseInt(properties.getProperty("read.seconds"))*1000);
					reader.stopReading();
					
					/*TagReadData[] tags = reader.read(15000);
					
					int size = tags.length;
					
					for(int i=0; i == size; i++){
						if(!currentEpcs.contains(tags[i].epcString())){
							currentEpcs.add(tags[i].epcString());
						}
					}*/
					
					if(firstUpdate){
			    		firstUpdate = false;
			    		previousEpcs = currentEpcs;
			    		currentEpcs.clear();
			    	}else{
			    		if(previousEpcs.containsAll(currentEpcs) && currentEpcs.containsAll(previousEpcs)){
			    			currentEpcs.clear();

			    		}else{
			    			previousEpcs = currentEpcs;
			    			currentEpcs.clear();
			    		}
			    	}
					
				} catch (IOException e1) {
					e1.printStackTrace();
				} catch (InterruptedException e1) {
					e1.printStackTrace();
				} /*catch (ReaderException e1) {
					e1.printStackTrace();
				}*/
				
				calculateItemsRead();
				
				updateTable(items);
				
			}
		});
    	
		timer.start();
    }
    
    public void calculateItemsRead(){
    	
    	for(String epc : currentEpcs){
    		
    		char[] ecpUnstrig = epc.toCharArray();
    		char[] upcChar = new char[8];
    		upcChar[0] = ecpUnstrig[0];
    		upcChar[1] = ecpUnstrig[1];
    		upcChar[2] = ecpUnstrig[2];
    		upcChar[3] = ecpUnstrig[3];
    		upcChar[4] = ecpUnstrig[4];
    		upcChar[5] = ecpUnstrig[5];
    		upcChar[6] = ecpUnstrig[6];
    		upcChar[7] = ecpUnstrig[7];
    		
    		String upc = upcChar.toString();
    		
    		if(itemName.containsKey(upc)){
    			int iq = itemQuantity.get(upc);
    			itemQuantity.put(upc, iq + 1);
    		}
    	}
    	
    	Set<String> keys = itemQuantity.keySet();
    	
    	for(String key : keys){
    		String name = itemName.get(key);
    		int quantity = itemQuantity.get(key);
    		
    		Item item = new Item(name, quantity);
    		items.add(item);
    	}
    	
    }
    
    private void createAndLoadItemsMap() {
		
		itemName = new HashMap<String, String>();
		itemName.put("00001234", "Camisa Branca P");
		itemName.put("00001235", "Camisa Branca M");
		itemName.put("00001236", "Camisa Branca G");
		
		itemQuantity = new HashMap<String, Integer>();
		itemQuantity.put("00001234", 0);
		itemQuantity.put("00001235", 0);
		itemQuantity.put("00001236", 0);
	}
    
	
	public void updateTable(ArrayList<Item> itens){
		        
        String[] colunas = {"ITEM", "QUANTIDADE"};
        content = new Object[itens.size()][2];

        int cont = 0;
        for(Item item:itens){
        	content[cont][0] = item.getName();
        	content[cont][1] = item.getQuantity();
        	cont++;
        }
        tblItems = new JTable(content, colunas);
        jScrollPane.setViewportView(tblItems); 
		
	}

	@Override
	public void tagRead(Reader reader, TagReadData t) {
		if(!currentEpcs.contains(t.epcString())){
			currentEpcs.add(t.epcString());
		}
		
	}

}
